package com.health.memberbackstage.conf;

import com.alibaba.fastjson.JSON;
import com.health.memberbackstage.filters.LoginInterceptor;
import com.health.memberbackstage.filters.VerifyTokenInterceptor;
import com.health.memberbackstage.pojo.R.Result;
import com.health.memberbackstage.pojo.R.ResultEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements InitializingBean {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().configurationSource(ccs());
        http.authorizeRequests()
                .antMatchers("/**").authenticated(); // 哪些资源必须登录
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        Result r = Result.fail(ResultEnum.NO_LOGIN);
                        response.setContentType("application/json;charset=utf-8");
                        response.getWriter().write(JSON.toJSONString(r));
                    }
                });

        http.addFilter(new LoginInterceptor(authenticationManager()))
                .addFilter(new VerifyTokenInterceptor(authenticationManager()));
    }

    private CorsConfigurationSource ccs() {
        UrlBasedCorsConfigurationSource ubccs = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfig = new CorsConfiguration();
        // 允许那些域的访问     *：表示所有域都能访问
        corsConfig.setAllowedOrigins(Arrays.asList("*"));
        // 允许那些访问方式的访问   *：表示所有方法都能访问
        corsConfig.setAllowedMethods(Arrays.asList("*"));
        // 跨域访问时，允许携带的请求头有哪些  *：表示所有请求头都能携带  (排除cookie)
        corsConfig.setAllowedHeaders(Arrays.asList("*"));
        //跨域访问时，允许携带的响应头有哪些  *：表示所有响应头都能携带  (排除cookie)
        corsConfig.setExposedHeaders(Arrays.asList("*"));
        // 允许携带cookie信息
        // corsConfig.setAllowCredentials();

        // 所有的资源方位都按照指定的corsConfig配置来进行跨域限定
        ubccs.registerCorsConfiguration("/**",corsConfig);

        return ubccs;
    }


    @Override
    public void afterPropertiesSet() throws Exception {

    }
}

